<template>
  <view class="order">
    <view class="topTab">
      <AtTabs
      :swipeable="false"
      :current="tabCurrent"
      :tabList="tagTable"
      @click="clickTab"
    ></AtTabs>
    </view>
    <scroll-view
      style="height: 100%;"
      :refresherEnabled="true"
      :scroll-y="true"
      :lowerThreshold="100"
      :refresherTriggered="isFresh"
      @refresherRefresh="refresherRefresh"
      @scrolltolower="loadMore"
    >
    <view v-if="tabDataList.length" class="orderItem" v-for="item in tabDataList" :key="item.o_order_code">
      <view class="topStatus">
        <view class="orderCode">订单号: <text style="font-size: 24rpx; position: relative; top: -5rpx;">{{item.o_order_code}}</text></view>
        <view class="status" :class="item.o_status == -1 ? 'cancleOrder': item.o_status == 0 ? 'willPayOrder' : item.o_status == 1 ? 'willGetGlass' : 'alreadyComplate'">
          {{item.o_status == 3 ? '已完成' : item.o_status == 0 ? '待支付' : item.o_status == 1 ? '待取镜' : item.o_status == 2 ? '已取镜': '已取消'}}
        </view>
      </view>
      <view class="middleContent" @tap.prevent="gotoPayHtml(item.o_order_code)">
        <view class="middleImg">
          <view class="imgBox">
            <image :src="imgUrl"/>
          </view>
          <view class="itemBox">
            <view class="order-item">眼镜数量 {{ item.o_glasses_num }}副</view>
            <view class="order-item">押金金额 ¥{{ item.o_money }}</view>
            <view class="order-item">下单时间 {{ item.o_start_time }}</view>
          </view>
        </view>
      </view>
      <view class="bottomOption">
          <view class="b_l">
              <view v-if="!!item.y_num" class="b_l_i">已取镜：{{ item.y_num }}副</view>
              <view v-if="item.o_status == 1">待取镜：{{ item.o_glasses_num - (item.y_num || 0) }}副</view>
          </view>
          <view class="optionBtn">
            <view class="cancelOrder" v-if="(item.o_status == 0 || item.o_status == 1) && !item.y_num" type="secondary" size="small" @tap.stop="cancelOrder(item, item.o_order_code, item.o_money, item.o_status)">取消订单</view>
            <AtButton v-if="item.o_status == 0" class="willPayOrder" type="primary" size="small" @click.stop="gotoPayHtml(item.o_order_code)">去支付</AtButton>
            <AtButton v-else-if="item.o_status == 1"  class="willGetGlass" type="primary" size="small"  @click.stop="gotoGetGlass(item.o_order_code)">去取镜</AtButton>
            <AtButton v-else type="primary" size="small"  class="alreadyComplate"  @click.stop="gotoPayHtml(item.o_order_code)">查看详情</AtButton>
          </view>
      </view>
    </view>
    <view v-if="noDataTrue" class="no-data">
      <view class="dataBg"></view>
      暂无数据
    </view>
    <AtLoadMore v-if="dataStatus" :status="loadMoreStatus"/>
  </scroll-view>
  <AtModal
    :isOpened="cancelOrderModel"
    title='取消订单'
    cancelText='取消'
    confirmText='确认'
    @close="cancelOrderModel = false"
    @cancel="cancelOrderModel = false"
    @confirm="handleConfirm"
    :content='"确认要取消订单编号为：" + orederCode.code +"的订单？" + (orederCode.status == 1 ? "订单押金¥" + orederCode.money + "将返回原账户,72小时内到账"  : "")'
  />
  </view>
</template>

<script setup>
import './index.scss'
import { AtButton, AtTabs, AtLoadMore, AtModal } from 'taro-ui-vue3'
import { reactive, ref } from 'vue';
import {queryOrderList, cancel_order} from '../../http/api'
import Taro, {useDidShow} from '@tarojs/taro'
function gotoGetGlass (code) {
  Taro.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (!res.subscriptionsSetting.mainSwitch
        || (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings['kVGxFfk0ZW0aGbWr97PbM-bPDmsM8vWIiNAy1L5jEgk']) == 'reject'
      ) {
          Taro.showModal({
            title: '温馨提示',
            showCancel: false,
            content: '为了您能接收到退款提醒消息，请打开设置勾选订阅接受通知消息',
            success: function (res) {
              if (res.confirm) {
                Taro.openSetting({
                  success: function (res) {
                    Taro.showModal({title: '温馨提示',
                    content: '订阅消息通知，方便给您退款通知',
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        Taro.requestSubscribeMessage({
                          tmplIds: ['kVGxFfk0ZW0aGbWr97PbM-bPDmsM8vWIiNAy1L5jEgk'],
                          complete: function (Subscribe) {
                          }
                        })
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }})
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }else {
          Taro.navigateTo({
            url: `/pages/QRCode/index?o_order_code=${code}`
          })

        }
      }
    })

}
const cancelOrderModel = ref(false)
const noDataTrue = ref(false)
const orederCode = reactive({
  code: "",
  item: {},
  money: 0,
  status: 0
})
const imgUrl = require('../index/imgs/e1.png')

const isFresh = ref(false)

const loadMoreStatus = ref('loading')

const dataStatus = ref(false)

const tabCurrent = ref(0)
const tabDataList = ref([])
const orderStatus = ref()
const totalNum = ref(0)
const page = ref(1)
const tagTable = ref([
    { title: '全部' },
    { title: '待支付' },
    { title: '待取镜' },
    { title: '已完成' },
])
function gotoPayHtml(code) {
  Taro.navigateTo({
    url: `/pages/orderDetail/index?o_order_code=${code}`
  })
}
// 上拉加载
function loadMore () {
  if (loadMoreStatus.value == 'loading') return
  dataStatus.value = true
  page.value += 1;
  if (totalNum.value == tabDataList.value.length) {
      dataStatus.value = true
      loadMoreStatus.value = 'noMore'
  } else {
    queryList()
  }

}
// 下拉刷新被触发
function refresherRefresh (e) {
  isFresh.value = true;
  page.value = 1
  queryOrderList({page: 1,o_status:orderStatus.value, page_size:5  }).then(res => {
    if (res.code == '1000') {
      tabDataList.value = [ ...res.data.data_list];
      noDataTrue.value = !tabDataList.value.length
      totalNum.value = res.data.total;
    }
    isFresh.value = false
    dataStatus.value = false
  })

}
// 取消订单
function cancelOrder (item, code, money, status) {
  cancelOrderModel.value = true
  orederCode.code = code;
  orederCode.item = item;
  orederCode.money = money;
  orederCode.status = status;
}

function handleConfirm () {
  cancel_order({o_order_code: orederCode.code}).then(res => {
    if (res.code == '1000') {
      Taro.showToast({
        title: '取消成功',
        icon: 'success',
        duration: 2000
      })
      cancelOrderModel.value = false
      tabDataList.value = []
      noDataTrue.value = false
      page.value = 1
      queryList()
    }

  })
}
function queryList () {
  loadMoreStatus.value = 'loading'
  queryOrderList({page: page.value,o_status:orderStatus.value,page_size: 5  }).then(res => {
    if (res.code == '1000') {
      tabDataList.value = [...tabDataList.value, ...res.data.data_list];
      noDataTrue.value = !tabDataList.value.length
      totalNum.value = res.data.total;
      loadMoreStatus.value = 'nomore'
    }

  })
}
function clickTab (val) {
  dataStatus.value = false
  tabCurrent.value = val
  page.value = 1
  tabDataList.value = []
  noDataTrue.value = false
  switch(val) {
    case 0: orderStatus.value = null;
    break;
    case 1: orderStatus.value = 0;
    break;
    case 2: orderStatus.value = 1;
    break;
    case 3: orderStatus.value = 3;
    break;
    // case 4: orderStatus.value = 3;
    // break;
    default: orderStatus.value = null;
  }
  queryList()
}

useDidShow(() => {
  var token_key_obj = Taro.getStorageSync('userData')
  if (token_key_obj) {
    tabDataList.value = []
    noDataTrue.value = false
    page.value = 1
    queryList()
  } else {
    Taro.showModal({
      title: '温馨提示',
      confirmText: '去登录',
      showCancel: true,
      content: '您现在是未登录状态，请登录之后查看个人订单',
      success: (res) => {
        if (res.confirm) {
          Taro.navigateTo({
            url: '/pages/login/index'
          })
        }
      }
    })
  }

})
Taro.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline']
})
</script>
